//
//  SingleRecordVC.m
//  record_plugin
//
//  Created by zqj on 2024/8/20.
//

#import "SingleRecordVC.h"
#import "SingleRecordResultVC.h"
#import <AVFoundation/AVFoundation.h>
#import "AuthSuccessView.h"
#import "AuthFailView.h"
#import "AnswerDisplayView.h"
#import "RecordEndView.h"
#import "TTSDisplayView.h"
#import "Constant.h"
#import "NetworkingTool.h"

@interface SingleRecordVC ()<AVDEngineDelegate,AVDAudioDelegate,AVDRoomJoinDelegate,AVDVideoDelegate,AVDAudioExportDelegate,AVDFirstFrameCallBack>
@property (weak, nonatomic) IBOutlet UILabel *timeLab;
@property (weak, nonatomic) IBOutlet UILabel *notifyLab;
@property (weak, nonatomic) IBOutlet UIView *bottomView;//底部交换区域
@property (weak, nonatomic) IBOutlet UIImageView *recordBg;
@property (weak, nonatomic) IBOutlet AVDVideoView *localRender;

@property (strong, nonatomic) AuthSuccessView *authSuccessView;
@property (strong, nonatomic) AuthFailView *authFailView;
@property (strong, nonatomic) AnswerDisplayView *answerDisplayView;
@property (strong, nonatomic) TTSDisplayView *ttsDisplayView;
@property (strong, nonatomic) RecordEndView *recordEndView;

@property (strong, nonatomic) NSString * avdToken;
@property (strong, nonatomic) NSString * accessToken;
@property (strong, nonatomic) NSString * avdUrl;
@property (strong, nonatomic) NSString * playerID;
@property (assign, nonatomic) NSInteger totalTime;
@property (assign, nonatomic) NSInteger startTime;

@property (strong, nonatomic) NSString *asrPath;//回答wav文件地址
@property (assign, nonatomic) BOOL isFacePass;//记录人脸对比是否通过
@property (assign, nonatomic) BOOL isVoicePass;//记录语音对比是否通过

@property (nonatomic, strong) AVDRoom *mRoom;
@property (nonatomic, strong) AVDVideo *mVideo;
@property (nonatomic, strong) AVDAudio *mAudio;
@property (nonatomic, strong) AVDAudioExport *mAudioExport;

@property (strong, nonatomic) NSTimer *timer;
@property (strong, nonatomic) CADisplayLink *link;
@property (nonatomic, assign) NSInteger ttsIndex;//当前播放ttsidx
@property (nonatomic, strong) TTSModel *ttsModel;//当前播放tts对象
@property (nonatomic, assign) NSInteger faceErrCount;//人脸对比错误次数



@end

@implementation SingleRecordVC

- (void)dealloc{
    NSLog(@"SingleRecordVC ==== dealloc");
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationItem.hidesBackButton = YES;
    [self.mTextArr removeAllObjects];
    [self getTTSList];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    // Do any additional setup after loading the view from its nib.
    self.title = @"视频录制";
    [self setupUI];
    [self configMoudle];
 
}

- (void)setupUI{
    self.notifyLab.text = @"请面向屏幕人脸识别";
    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateTime)];
    link.preferredFramesPerSecond = 1;
    [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    self.link = link;
    self.localRender.firstFrameCallback = self;
    [self.localRender setScalingType:Scale_Aspect_Full];
}

- (void)configMoudle{
    self.mRoom = [AVDRoom obtain:self.roomID];
    self.mRoom.delegate = self;
    self.mVideo = [AVDVideo getVideo:self.mRoom];
    self.mVideo.delegate = self;
    self.mAudio = [AVDAudio getAudio:self.mRoom];
    self.mAudio.delegate = self;
    self.mAudioExport = [AVDAudioExport getAudioExport:self.mRoom];
    self.mAudioExport.delegate = self;
  
    self.userID = [NSUUID UUID].UUIDString;
    AVDUser *user = [[AVDUser alloc]initWithUserId:self.userID userName:@"record_plugin" userData:nil];
    [self.mRoom joinWithUser:user delegate:self];
    
}

-(void)onJoinResult:(AVDResult)result{
    if (result == AVD_Success) {
        NSLog(@"房间加入成功");
        //[self callBack:@"0" msg:@"录制模块初始化成功"];
        [self.mAudio openMicrophone];
        [self.mVideo publishLocalCamera];
    }else{
        NSLog(@"间加入失败");
    }
}


- (NSMutableArray *)mTextArr{
    if (!_mTextArr) {
        _mTextArr = [NSMutableArray array];
    }
    return _mTextArr;
}

- (AuthSuccessView *)authSuccessView{
    if (!_authSuccessView) {
        _authSuccessView = [AuthSuccessView instance];
        WeakSelf;
        _authSuccessView.recordBlock = ^{
            NSLog(@"认证通过，开始录制");
            weakSelf.notifyLab.text = @"请仔细聆听";
            [weakSelf.authSuccessView removeFromSuperview];
            [weakSelf startServerRecord];
            [weakSelf creteTTSPlayer];
            [weakSelf cycleFaceDetectPerSec];
           
        };
        _authSuccessView.frame = self.bottomView.bounds;
    }
    return _authSuccessView;
}

- (AnswerDisplayView *)answerDisplayView{
    if (!_answerDisplayView) {
        _answerDisplayView = [AnswerDisplayView instance];
        _answerDisplayView.frame = self.bottomView.bounds;
    }
    return _answerDisplayView;
}

- (TTSDisplayView *)ttsDisplayView{
    if (!_ttsDisplayView) {
        _ttsDisplayView = [TTSDisplayView instance];
        _ttsDisplayView.frame = self.bottomView.bounds;
    }
    
    return _ttsDisplayView;
}

- (AuthFailView *)authFailView{
    if (!_authFailView) {
        _authFailView = [AuthFailView instance];
        WeakSelf;
        _authFailView.recBlock = ^{
            weakSelf.isFacePass = NO;
            [weakSelf.authFailView removeFromSuperview];
            NSLog(@"认证失败，继续录制");
            weakSelf.isFacePass = NO;
            weakSelf.notifyLab.text = @"请仔细聆听";
            [weakSelf.authSuccessView removeFromSuperview];
            [weakSelf startServerRecord];
            [weakSelf creteTTSPlayer];
            [weakSelf cycleFaceDetectPerSec];
        };
        _authFailView.authBlock = ^{
            [weakSelf.authFailView removeFromSuperview];
            NSLog(@"认证失败，重新认证");
            [[NetworkingTool sharedInstance] faceDetect:weakSelf.firstFileUrl localImg:[weakSelf.localRender captureRenderImage:100] handler:^(NSInteger code,double similarity) {
                if (code == 200 && similarity > self.similarity) {
                    weakSelf.isFacePass = YES;
                    [weakSelf.bottomView addSubview:weakSelf.authSuccessView];
                }else {
                    [weakSelf.bottomView addSubview:weakSelf.authFailView];
                }
                } failure:^(NSError * _Nonnull error) {
                    [weakSelf.bottomView addSubview:weakSelf.authFailView];
                }];
        };
        _authFailView.frame = self.bottomView.bounds;
    }
    return _authFailView;
}

- (RecordEndView *)recordEndView{
    if (!_recordEndView) {
        _recordEndView = [RecordEndView instance];
        WeakSelf;
        _recordEndView.rerecordBlock = ^(UtilityType type) {//第一个按钮
            [weakSelf.recordEndView removeFromSuperview];
            if (type == AnswerComparison) {//重播
                weakSelf.ttsIndex = weakSelf.ttsIndex - 1;
                [weakSelf playTTS:weakSelf.mTextArr[weakSelf.ttsIndex]];
            }else {//重录
                [weakSelf reRecord];
            }
        };
        _recordEndView.continueBlock = ^(UtilityType type){//第二个按钮
            [weakSelf.recordEndView removeFromSuperview];
            if (type == AnswerComparison) {//继续
                if (weakSelf.ttsIndex < weakSelf.mTextArr.count) {
                    TTSModel *model = weakSelf.mTextArr[weakSelf.ttsIndex];
                    [weakSelf playTTS:model];
                }else{
                    [weakSelf go2ResulteVC];
                }
            }else if (type == RecordEnd){//继续
                [weakSelf go2ResulteVC];
            }else if (type == FaceComparison){//确认本人
                [weakSelf go2ResulteVC];
            }
           
        };
        _recordEndView.frame = self.bottomView.bounds;
    }
    return _recordEndView;
}

- (void)reRecord{
    self.ttsIndex = 0;
    self.isVoicePass = NO;
    self.isFacePass = NO;
    WeakSelf;
    [[NetworkingTool sharedInstance] faceDetect:self.firstFileUrl localImg:[self.localRender captureRenderImage:100] handler:^(NSInteger code,double similarity) {
        NSLog(@"xxxx 首次人脸对比返回结果 code = %ld 相似度 = %f",code,similarity);
        if (code == 200 && similarity > weakSelf.similarity) {
            weakSelf.isFacePass = YES;
            [weakSelf.bottomView addSubview:weakSelf.authSuccessView];
        }else {
            [weakSelf.bottomView addSubview:weakSelf.authFailView];
        }
        } failure:^(NSError * _Nonnull error) {
            [weakSelf.bottomView addSubview:weakSelf.authFailView];
        }];
//    [[NetworkingTool  sharedInstance] stopServerRecordWithHandler:^(NSString * _Nonnull palyUrl) {
//       
//    } failure:^(NSError * _Nonnull error) {
//        
//    }];
//    [self startServerRecord];
//    [self creteTTSPlayer];
//    [self cycleFaceDetectPerSec];

}

- (void)go2ResulteVC{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    WeakSelf;
    [[NetworkingTool sharedInstance] stopServerRecordWithHandler:^(NSString * _Nonnull palyUrl) {
        
        NSBundle *SDKBundle = [NSBundle bundleForClass:[SingleRecordResultVC class]];
        SingleRecordResultVC * vc = [[SingleRecordResultVC alloc] initWithNibName:@"SingleRecordResultVC" bundle:SDKBundle];
        vc.videoUrl = palyUrl;
        vc.isFacePass =  weakSelf.isFacePass;
        vc.isVoicePass = weakSelf.isVoicePass;
        vc.placeholderImg = [weakSelf.localRender captureRenderImage:100];
        vc.block = ^(NSString * _Nonnull videoUrl) {
            [weakSelf releaseResource];
            [weakSelf callBackStatus:@"0" msg:@"录制成功" file:videoUrl];
        };
        vc.remakeblock = ^{
            [weakSelf reRecord];
        };
       [weakSelf.navigationController pushViewController:vc animated:YES];
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"停止服务器录制失败");
        [weakSelf callBackStatus:@"-1006" msg:@"停止服务器失败" file:@""];
    }];
}

- (void)releaseResource{
    [[NetworkingTool sharedInstance] cancleReq];
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    if (self.link) {
        [self.link invalidate];
        self.link = nil;
    }
    if (self.mRoom) {
        [self.mRoom close];
        [self.mRoom destory];
        self.mRoom = nil;
    }
    if (self.authFailView) {
        [self.authFailView removeFromSuperview];
        self.authFailView = nil;
    }
    if (self.authSuccessView) {
        [self.authSuccessView removeFromSuperview];
        self.authSuccessView = nil;
    }
    if (self.ttsDisplayView) {
        [self.ttsDisplayView removeFromSuperview];
        self.ttsDisplayView = nil;
    }
}

- (IBAction)cancelRecClicked:(UIButton *)sender {
    [[NetworkingTool sharedInstance] cancleReq];
    if (self.mAudioExport) {
        [self.mAudioExport stopExport];
    }
    if ([NetworkingTool sharedInstance].playerID) {
        [[NetworkingTool sharedInstance] stopTTSPlayerWithHandler:^{
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
    }
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    if (self.link) {
        [self.link invalidate];
        self.link = nil;
    }
    if (self.mRoom) {
        [self.mRoom close];
        [self.mRoom destory];
        self.mRoom = nil;
    }
    if (self.authFailView) {
        [self.authFailView removeFromSuperview];
        self.authFailView = nil;
    }
    if (self.authSuccessView) {
        [self.authSuccessView removeFromSuperview];
        self.authSuccessView = nil;
    }
    if (self.ttsDisplayView) {
        [self.ttsDisplayView removeFromSuperview];
        self.ttsDisplayView = nil;
    }

    [self.navigationController popViewControllerAnimated:YES];
}
 
//- (void)viewWillLayoutSubviews{
//    [super viewWillLayoutSubviews];
//    self.authSuccessView.frame = self.bottomView.bounds;
//    self.authFailView.frame = self.bottomView.bounds;
//    self.answerDisplayView.frame = self.bottomView.bounds;
//    self.ttsDisplayView.frame = self.bottomView.bounds;
//    self.recordEndView.frame = self.bottomView.bounds;
//
//}


- (void)updateTime{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    self.timeLab.text = currentDateString;
}



#pragma mark videoDelegate
- (void)onPublishLocalResult:(AVDResult)result deviceId:(AVDDeviceId)fromId{
    if (self.delegate && [self.delegate respondsToSelector:@selector(onPulishVideoStatus:)]) {
        [self.delegate onPulishVideoStatus:result == AVD_Success];
    }
    [self.mVideo attachRenderWithDeviceId:fromId render:self.localRender];
   
  
}

#pragma mark AVDFirstFrameCallBack
- (void)onFirstFrameArrived:(id<AVDVideoRenderer>)render{
    //NSLog(@"传人的人脸数据 = %@",self.firstFileUrl);
    NSLog(@"xxxx 视频渲染成功 开启首次人脸对比");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            //开始截图图片进行人脸检测
            WeakSelf;
            [[NetworkingTool sharedInstance] faceDetect:self.firstFileUrl localImg:[self.localRender captureRenderImage:100] handler:^(NSInteger code,double similarity) {
                NSLog(@"xxxx 首次人脸对比返回结果 code = %ld 相似度 = %f",code,similarity);
                if (code == 200 && similarity > weakSelf.similarity) {
                    weakSelf.isFacePass = YES;
                    [weakSelf.bottomView addSubview:weakSelf.authSuccessView];
                }else {
                    [weakSelf.bottomView addSubview:weakSelf.authFailView];
                }
                } failure:^(NSError * _Nonnull error) {
                    [weakSelf.bottomView addSubview:weakSelf.authFailView];
                }];
        });
    });
      
}

#pragma mark audioDelegate
- (void)onMediaPlayNotify:(AVDRoomId)roomId playId:(NSString *)pid userId:(AVDUserId)userId status:(enum AVDMediaPlayEvents)status{
    NSLog(@"TTS 播放通知 总时长 =%ld",self.totalTime);
    if (status == MediaPlayEventsStarted) {
        self.startTime = [[NSDate date] timeIntervalSince1970]*1000;
        [self.mAudio setSpeakerMode:SM_Handfree];
        [self.bottomView addSubview:self.ttsDisplayView];
    }
    if (status == MediaPlayEventsStoped) {//tts播放完毕需要根据当前话术是否需要回答判断，不需要回答则播放下一条，需要回答则提示回答并根据回答配置时间显示结果
        if (self.ttsModel.answerprompt.length) {//当前话术需要回答
            [self startAudioLocalRecord];
            NSInteger time = self.ttsModel.responsetime;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self stopAudioLocalRecordAndAsr];
            });
        }else{//不需要回答播放下一个
            if (self.ttsIndex < self.mTextArr.count) {
                TTSModel *model = self.mTextArr[self.ttsIndex];
                [self playTTS:model];
            }else{
                [self startAudioLocalRecord];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self stopAudioLocalRecordAndAsr];
                });
            }

        }
    }
}

//tts播放进度回调
- (void)onMediaPlayNotify:(NSUInteger)currentValue{
    
    currentValue = [[NSDate date] timeIntervalSince1970] *1000 - self.startTime;
    float progress = (float)currentValue / self.totalTime;
    //NSLog(@"TTS 播放进度通知 prgress = %f time = %ld",progress,currentValue);
    // 更新 UILabel 的文本
    [self.ttsDisplayView updateProgress:progress];
 
}

- (void)startAudioLocalRecord{
    [self.ttsDisplayView removeFromSuperview];
    NSLog(@"开始导出本地音频");
    if ([[NSFileManager defaultManager] fileExistsAtPath:asrPcmPath]) {
        [[NSFileManager defaultManager] removeItemAtPath:asrPcmPath error:nil];
    }
    if ([[NSFileManager defaultManager] fileExistsAtPath:asrWavPath]) {
        [[NSFileManager defaultManager] removeItemAtPath:asrWavPath error:nil];
    }
    [self.mAudio setSpeakerMode:SM_Handfree];
    [self.mAudioExport selectUser4Export:self.userID sampleRate:16000 channels:1];
    [self.bottomView addSubview:self.answerDisplayView];
    [self.answerDisplayView updateIsAnswer:YES content:nil];

}

- (void)stopAudioLocalRecordAndAsr{
    [self.mAudioExport stopExport];
    [self.mAudio setSpeakerMode:SM_Receiver];

    NSLog(@"结束导出本地音频");
    self.asrPath = [self getAndCreatePlayableFileFromPcmData: [NSData dataWithContentsOfFile:self.asrPath]];
    [[NetworkingTool sharedInstance] audio2TextAsr:self.asrPath handler:^(NSString * _Nonnull asrTxt) {
        [self.answerDisplayView updateIsAnswer:NO content:asrTxt];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.answerDisplayView removeFromSuperview];
        });
        if ([self checkAnswer:asrTxt]) {//回答正确播放下一条
            self.isVoicePass = YES;
            if (self.ttsIndex < self.mTextArr.count) {
                TTSModel *model = self.mTextArr[self.ttsIndex];
                [self playTTS:model];
            }else{
                if(self.ttsIndex == self.mTextArr.count){//播放完成
                    if (self.faceErrCount > 5) {//人脸对比超过次数
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self.bottomView addSubview:self.recordEndView];
                            [self.recordEndView setUtilityType:FaceComparison];
                        });
                    }else{
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self.bottomView addSubview:self.recordEndView];
                            [self.recordEndView setUtilityType:RecordEnd];
        
                        });
                    }
                   
                }
            }

        }else{//识别不清楚或者不包含正确回答
            self.isVoicePass = NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.bottomView addSubview:self.recordEndView];
                [self.recordEndView setUtilityType:AnswerComparison];
            });
        }
       
    } failure:^(NSError * _Nonnull error) {
        self.isVoicePass = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.bottomView addSubview:self.recordEndView];
            [self.recordEndView setUtilityType:AnswerComparison];
        });

    }];
}

- (BOOL)checkAnswer:(NSString *)asrStr{
    BOOL containsCharacter = NO;

    NSString *stringToCheck = asrStr.length?asrStr:@"我的回答正确"; // 替换为你要检查的字符串
    NSArray *unAnswerArray = @[@"不是",@"否",@"不正确",] ;
   
    // 要检查的字符
    NSMutableArray *charArray = [@[@"是",@"我是",@"是的",@"对", @"正确", @"对的"] mutableCopy];
    [charArray addObject:self.ttsModel.customeranswer];
    for (NSString *character in charArray) {
        if ([stringToCheck rangeOfString:character].location != NSNotFound) {
            containsCharacter = YES;
            break; // 找到一个就可以退出循环
        }
    }
    
    for (NSString *character in unAnswerArray) {
        if ([stringToCheck rangeOfString:character].location != NSNotFound) {
            containsCharacter = NO;
            break; // 找到一个就可以退出循环
        }
    }

    if (containsCharacter) {
        NSLog(@"字符串包含'是'、'正确'或'对'");
    } else {
        NSLog(@"字符串不包含'是'、'正确'或'对'");
    }
    return containsCharacter;
}

#pragma mark AudioExportDelegate
- (void)onAudioStreamOut:(NSData *)data userId:(NSString *)userId timestamp:(NSInteger)timestamp sampleRate:(NSInteger)sampleRate channels:(NSInteger)channels{
    //NSLog(@"开始导出音频");
   [self saveAudioDataToPCMFile:data];
}

- (void)saveAudioDataToPCMFile:(NSData *)audioData {
    NSString *filePath = asrPcmPath;
    self.asrPath = filePath;
    NSFileManager *fileManager = [NSFileManager defaultManager];
      if (![fileManager fileExistsAtPath:filePath]) {
          [fileManager createFileAtPath:filePath contents:nil attributes:nil];
      }
      NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
      if (fileHandle) {
          [fileHandle seekToEndOfFile];
          [fileHandle writeData:audioData];
          [fileHandle closeFile];
      } else {
          NSLog(@"Unable to open file for writing.");
      }
}

-(void)savePcmAudioRawData:(NSData *)data {
    NSString *filePath = asrPcmPath;
    self.asrPath = filePath;
    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
        BOOL success =[data writeToFile:filePath atomically:YES];
        if(success){
            NSLog(@"asr开始写入成功");
        } else {
            NSLog(@"asr开始写入失败");
        }
    }
    else {
        NSFileHandle *fileHandle =[NSFileHandle fileHandleForUpdatingAtPath:filePath];
        [fileHandle seekToEndOfFile];
        [fileHandle writeData:data];
        [fileHandle closeFile]; //将节点跳到文件的末尾[fileHandle writeData:data];[fileHandle closeFile];NSLog(@"asr最后写入成功");11
    }
}

// 将pcm存为wav文件
- (NSString *) getAndCreatePlayableFileFromPcmData:(NSData *)pcmData{
    NSString *wavFilePath = asrWavPath;
    short NumChannels = 1;       //录音通道数
    short BitsPerSample = 16;    //线性采样位数
    int SamplingRate = 16000;     //录音采样率(Hz)
    int numOfSamples = (int)pcmData.length;
    
    int ByteRate = NumChannels*BitsPerSample*SamplingRate/8;
    short BlockAlign = NumChannels*BitsPerSample/8;
    int DataSize = NumChannels*numOfSamples*BitsPerSample/8;
    int chunkSize = 16;
    int totalSize = 46 + DataSize;
    short audioFormat = 1;
    
    const char *wavFilePathChar = [wavFilePath cStringUsingEncoding:NSUTF8StringEncoding];
    @synchronized (self) {
        FILE *fout = fopen(wavFilePathChar, "w");
        if(fout == NULL){
            return nil;
        }
        
        fwrite("RIFF", sizeof(char), 4,fout);
        fwrite(&totalSize, sizeof(int), 1, fout);
        fwrite("WAVE", sizeof(char), 4, fout);
        fwrite("fmt ", sizeof(char), 4, fout);
        fwrite(&chunkSize, sizeof(int),1,fout);
        fwrite(&audioFormat, sizeof(short), 1, fout);
        fwrite(&NumChannels, sizeof(short),1,fout);
        fwrite(&SamplingRate, sizeof(int), 1, fout);
        fwrite(&ByteRate, sizeof(int), 1, fout);
        fwrite(&BlockAlign, sizeof(short), 1, fout);
        fwrite(&BitsPerSample, sizeof(short), 1, fout);
        fwrite("data", sizeof(char), 4, fout);
        fwrite(&DataSize, sizeof(int), 1, fout);
        
        fclose(fout);
        NSFileHandle *handle;
        handle = [NSFileHandle fileHandleForUpdatingAtPath:wavFilePath];
        [handle seekToEndOfFile];
       // self.recordedData 为需要保存的pcm数据
        [handle writeData:pcmData];
        [handle closeFile];
        return wavFilePath;
    }
}
#pragma mark httpReq 先获取acessToken->avdser->initEng
- (void)getTTSList{
    WeakSelf;
    [[NetworkingTool sharedInstance] getTSSListWithCode:self.productCode handler:^(NSMutableArray * _Nonnull ttsArr) {
        [weakSelf.mTextArr addObjectsFromArray:ttsArr];
        [ttsArr enumerateObjectsUsingBlock:^(TTSModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog(@"%@",obj);
            [weakSelf ttsText2Audio:obj];
//            if (!obj.filepath.length) {//返回的音频文件有值则播放否则需要取文本内容转tts语音来播放
//                [self ttsText2Audio:obj];
//            }
        }];
    } failure:^(NSError * _Nonnull error) {
        [weakSelf callBackStatus:@"-1001" msg:@"获取话术列表失败" file:@""];
    }];
}

- (void)ttsText2Audio:(TTSModel *)model{
    WeakSelf;
    [[NetworkingTool sharedInstance] text2Tss:model.agentquestion handler:^(NSString * _Nonnull ttsUrl) {
        model.filepath = ttsUrl;
        NSLog(@"xxxx tts转化成功");
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"xxxx tts转化失败 ");
        [weakSelf callBackStatus:@"-1002" msg:@"话术转TTS语音失败" file:@""];
        [weakSelf alertMsg:@"话术转TTS语音失败,请重新开始。"];
    }];

}

- (void)creteTTSPlayer{
    [[NetworkingTool sharedInstance] creteTTSPlayer:self.roomID handler:^(NSString * _Nonnull playerID) {
        self.playerID = playerID;
        [self playTTS:self.mTextArr[self.ttsIndex]];
    } failure:^(NSError * _Nonnull error) {
        [self callBackStatus:@"-1004" msg:@"创建TTS播放器失败" file:@""];
    }];

}

- (void)playTTS:(TTSModel *)model{
    self.startTime = 0;
    self.ttsModel = model;
    self.ttsIndex += 1;
    [self.ttsDisplayView updateNum:[NSString stringWithFormat:@"%ld/%ld",self.ttsIndex,self.mTextArr.count] content:model.agentquestion];
    [[NetworkingTool sharedInstance] playTTS:model.filepath handler:^(NSInteger totalTime) {
        self.totalTime = totalTime;
    } failure:^(NSError * _Nonnull error) {
        [self callBackStatus:@"-1005" msg:@"播放TTS话术失败" file:@""];
    }];
}


- (void)stopTTSPlayer{
    [[NetworkingTool sharedInstance] stopTTSPlayerWithHandler:^{
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

- (void)startServerRecord{
    [[NetworkingTool sharedInstance] startServerRecord:self.roomID handler:^{
        
    } failure:^(NSError * _Nonnull error) {
        [self callBackStatus:@"-1003" msg:@"开启服务器录制失败" file:@""];
        [self alertMsg:@"服务器录制开启失败，请重新开始。"];
    }];
}

- (void)faceDetect:(UIImage *)localImg{
    //200对比通过 500人脸不在框 600多人在框
    WeakSelf;
    [[NetworkingTool sharedInstance] faceDetect:self.firstFileUrl localImg:localImg handler:^(NSInteger code,double similarity) {
        if (code == 200 ) {
            if (similarity > weakSelf.similarity) {
                weakSelf.recordBg.image = UIImageWithName(@"signal_blue");
                weakSelf.notifyLab.text = @"请仔细聆听";
            }else{
                weakSelf.recordBg.image = UIImageWithName(@"singal_red");
                weakSelf.notifyLab.text = @"人脸检查分数过低";
            }
           
        }else if (code == 500){
            weakSelf.faceErrCount += 1;
            weakSelf.recordBg.image = UIImageWithName(@"singal_red");
            weakSelf.notifyLab.text = @"请不要离开视频拍摄范围";
        }else if(code == 600){
            weakSelf.notifyLab.text = @"请不要出现多张人脸在框内";
            weakSelf.recordBg.image = UIImageWithName(@"singal_red");
            NSLog(@"检测到多张人脸在框");
        }
    } failure:^(NSError * _Nonnull error) {
        weakSelf.recordBg.image = UIImageWithName(@"singal_red");
        weakSelf.notifyLab.text = @"请不要离开视频拍摄范围";
    }];
    
}


 
- (void)cycleFaceDetectPerSec{
    WeakSelf;
    self.timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf faceDetect:[weakSelf.localRender captureRenderImage:100]];
        });
    }];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}


- (void)callBackStatus:(NSString *)status msg:(NSString *)msg file:(NSString *)videoUrl{
    if (self.delegate && [self.delegate respondsToSelector:@selector(onRecordStatus:msg:videoUrl:)]) {
        [self.delegate onRecordStatus:status msg:msg  videoUrl:videoUrl];
    }
}

- (void)alertMsg:(NSString *)msg{
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self cancelRecClicked:nil];
    }];
    [ac addAction:cancle];
    [self presentViewController:ac animated:YES completion:nil];
}


@end
